package com.lcifn.middleware.rpc.server;

import java.util.HashMap;
import java.util.Map;

/**
 * 服务提供注册
 * @author lichao
 * @date 2021/2/1 14:24
 */
public class ServiceProviderRegistry {

    // 服务Class对象和服务对象Map
    private final Map<Class, Object> serviceClassMap = new HashMap<>();
    // 服务类名和服务对象Map
    private final Map<String, Object> serviceNameMap = new HashMap<>();
    // 单例
    private static ServiceProviderRegistry registry;

    /**
     * 获取单例
     * @return
     */
    public static ServiceProviderRegistry getInstance() {
        if (registry == null) {
            registry = new ServiceProviderRegistry();
        }
        return registry;
    }

    private ServiceProviderRegistry() {

    }

    /**
     * 注册服务
     * @param serviceClass
     * @param service
     * @param <T>
     */
    public <T> void addService(Class<? extends T> serviceClass, T service) {
        serviceClassMap.putIfAbsent(serviceClass, service);
        serviceNameMap.putIfAbsent(serviceClass.getCanonicalName(), service);
    }

    /**
     * 获取服务
     * @param serviceClassName
     * @return
     */
    public Object getService(String serviceClassName) {
        return serviceNameMap.get(serviceClassName);
    }
}
